package com.knowledgegraph.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.knowledgegraph.common.Result;
import com.knowledgegraph.entity.Relation;
import com.knowledgegraph.service.RelationService;
import com.knowledgegraph.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 关系管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/relations")
@CrossOrigin
public class RelationController {

    @Autowired
    private RelationService relationService;

    /**
     * 创建关系
     */
    @PostMapping("/create")
    public Result<Relation> createRelation(@RequestBody Relation relation) {
        try {
            log.info("接收到创建关系请求: {}", relation);
            Long userId = SecurityUtil.getCurrentUserId();
            
            boolean success = relationService.createRelation(relation, userId);
            if (success) {
                return Result.success( "创建关系成功",relation);
            } else {
                return Result.error("创建关系失败");
            }
        } catch (Exception e) {
            log.error("创建关系失败: {}", e.getMessage(), e);
            return Result.error("创建关系失败: " + e.getMessage());
        }
    }

    /**
     * 更新关系
     */
    @PostMapping("/update")
    public Result<Relation> updateRelation(@RequestBody Relation relation) {
        try {
            log.info("接收到更新关系请求，ID: {}", relation.getId());
            Long userId = SecurityUtil.getCurrentUserId();
            
            boolean success = relationService.updateRelation(relation, userId);
            if (success) {
                return Result.success("更新关系成功",relation);
            } else {
                return Result.error("更新关系失败");
            }
        } catch (Exception e) {
            log.error("更新关系失败: {}", e.getMessage(), e);
            return Result.error("更新关系失败: " + e.getMessage());
        }
    }

    /**
     * 删除关系
     */
    @PostMapping("/delete")
    public Result<Boolean> deleteRelation(@RequestBody Map<String, Long> params) {
        try {
            Long relationId = params.get("id");
            log.info("接收到删除关系请求，ID: {}", relationId);
            Long userId = SecurityUtil.getCurrentUserId();
            
            boolean success = relationService.deleteRelation(relationId, userId);
            if (success) {
                return Result.success("删除关系成功",true );
            } else {
                return Result.error("删除关系失败");
            }
        } catch (Exception e) {
            log.error("删除关系失败: {}", e.getMessage(), e);
            return Result.error("删除关系失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除关系
     */
    @PostMapping("/batch-delete")
    public Result<Boolean> batchDeleteRelations(@RequestBody Map<String, List<Long>> params) {
        try {
            List<Long> relationIds = params.get("ids");
            log.info("接收到批量删除关系请求，数量: {}", relationIds.size());
            Long userId = SecurityUtil.getCurrentUserId();
            
            boolean success = relationService.batchDeleteRelations(relationIds, userId);
            if (success) {
                return Result.success("批量删除关系成功",true);
            } else {
                return Result.error("批量删除关系失败");
            }
        } catch (Exception e) {
            log.error("批量删除关系失败: {}", e.getMessage(), e);
            return Result.error("批量删除关系失败: " + e.getMessage());
        }
    }

    /**
     * 获取关系详情
     */
    @PostMapping("/detail")
    public Result<Relation> getRelationDetail(@RequestBody Map<String, Long> params) {
        try {
            Long relationId = params.get("id");
            Long userId = SecurityUtil.getCurrentUserId();
            log.info("接收到获取关系详情请求，ID: {}, 用户ID: {}", relationId, userId);
            
            Relation relation = relationService.getById(relationId);
            if (relation != null) {
                // 检查是否是当前用户创建的关系
                if (!userId.equals(relation.getCreatorId())) {
                    return Result.error("您没有权限查看此关系");
                }
                return Result.success(relation);
            } else {
                return Result.error("关系不存在");
            }
        } catch (Exception e) {
            log.error("获取关系详情失败: {}", e.getMessage(), e);
            return Result.error("获取关系详情失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询关系
     */
    @PostMapping("/list")
    public Result<Map<String, Object>> getRelations(@RequestBody Map<String, Object> params) {
        try {
            log.info("接收到分页查询关系请求: {}", params);
            
            // 获取分页参数
            int page = params.containsKey("page") ? Integer.parseInt(params.get("page").toString()) : 1;
            int pageSize = params.containsKey("pageSize") ? Integer.parseInt(params.get("pageSize").toString()) : 10;
            
            // 创建分页对象
            Page<Relation> pageRequest = new Page<>(page, pageSize);
            
            // 默认只查询当前用户的数据
            Long userId = SecurityUtil.getCurrentUserId();
            params.put("creatorId", userId);
            
            // 执行分页查询
            IPage<Relation> pageResult = relationService.getRelationsWithPagination(pageRequest, params);
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("data", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("current", pageResult.getCurrent());
            result.put("pageSize", pageResult.getSize());
            
            log.info("分页查询关系成功，总数: {}, 当前页数据: {}", pageResult.getTotal(), pageResult.getRecords().size());
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("分页查询关系失败: {}", e.getMessage(), e);
            return Result.error("分页查询关系失败: " + e.getMessage());
        }
    }

    /**
     * 获取实体的关系
     */
    @PostMapping("/entity-relations")
    public Result<List<Relation>> getEntityRelations(@RequestBody Map<String, Long> params) {
        try {
            Long entityId = params.get("entityId");
            Long userId = SecurityUtil.getCurrentUserId();
            log.info("接收到获取实体关系请求，实体ID: {}, 用户ID: {}", entityId, userId);
            
            // 添加用户ID参数，确保只查询当前用户的关系
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("entityId", entityId);
            queryParams.put("creatorId", userId);
            
            List<Relation> relations = relationService.getRelationsByEntityId(entityId);
            return Result.success(relations);
            
        } catch (Exception e) {
            log.error("获取实体关系失败: {}", e.getMessage(), e);
            return Result.error("获取实体关系失败: " + e.getMessage());
        }
    }

    /**
     * 获取全局统计数据
     */
    @PostMapping("/stats")
    public Result<Map<String, Object>> getStats() {
        try {
            Long userId = SecurityUtil.getCurrentUserId();
            log.info("接收到获取统计数据请求，用户ID: {}", userId);
            
            // 改为获取用户统计数据，而不是全局统计
            Map<String, Object> stats = relationService.getUserStatistics(userId);
            return Result.success(stats);
            
        } catch (Exception e) {
            log.error("获取全局统计数据失败: {}", e.getMessage(), e);
            return Result.error("获取全局统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户统计数据
     */
    @PostMapping("/user-stats")
    public Result<Map<String, Object>> getUserStats() {
        try {
            Long userId = SecurityUtil.getCurrentUserId();
            log.info("接收到获取用户统计数据请求，用户ID: {}", userId);
            
            Map<String, Object> stats = relationService.getUserStatistics(userId);
            return Result.success(stats);
            
        } catch (Exception e) {
            log.error("获取用户统计数据失败: {}", e.getMessage(), e);
            return Result.error("获取用户统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 导入关系
     */
    @PostMapping("/import")
    public Result<Map<String, Object>> importRelations(@RequestParam("file") MultipartFile file) {
        try {
            log.info("接收到导入关系请求，文件名: {}", file.getOriginalFilename());
            Long userId = SecurityUtil.getCurrentUserId();
            
            Map<String, Object> result = relationService.importRelationsFromFile(file, userId);
            if (Boolean.TRUE.equals(result.get("success"))) {
                return Result.success(result.get("message").toString(),result);
            } else {
                return Result.error(result.get("message").toString());
            }
            
        } catch (Exception e) {
            log.error("导入关系失败: {}", e.getMessage(), e);
            return Result.error("导入关系失败: " + e.getMessage());
        }
    }

    /**
     * 导出关系
     */
    @PostMapping("/export")
    public ResponseEntity<String> exportRelations(@RequestBody Map<String, Object> params, HttpServletResponse response) {
        try {
            log.info("接收到导出关系请求: {}", params);
            
            // 默认只导出当前用户的数据
            Long userId = SecurityUtil.getCurrentUserId();
            params.put("creatorId", userId);
            
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = "关系数据_" + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            
            // 执行导出
            relationService.exportRelationsToExcel(params, response);
            
            return new ResponseEntity<>("导出成功", HttpStatus.OK);
            
        } catch (IOException e) {
            log.error("导出关系失败: {}", e.getMessage(), e);
            return new ResponseEntity<>("导出关系失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}